package com.seeyon.apps.ddkk.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.common.collect.Maps;
import com.seeyon.apps.kk.util.JdbcAgentUtil;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.ctp.common.content.affair.constants.StateEnum;
import com.seeyon.ctp.common.dao.BaseDao;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.util.FlipInfo;

public class QiangsDaoImpl extends BaseDao implements QiangsDao {
    private static final Log log = LogFactory.getLog(QiangsDaoImpl.class);

    @Override
    public List<Map> getAffairListByMemberIdAndState(Long memberId,
                                                     List<Long> formIds, StateEnum state) throws BusinessException {
        // TODO Auto-generated method stub
        StringBuffer sb = new StringBuffer("SELECT id,receive_time,subject,form_app_id,form_recordid");
        sb.append(" FROM ctp_affair WHERE member_id=:memberId AND state=:state");
        sb.append(" AND form_app_id IN(:formId) AND is_delete=:del");
        Map<String, Object> map = new HashMap();
        map.put("memberId", memberId);
        map.put("state", state.key());
        map.put("formId", formIds);
        map.put("del", 0);
        return JdbcAgentUtil.doQuery(sb.toString(), map);
    }

    @Override
    public Date validateLetterState(FormBean formBean, Map param) throws BusinessException {
        // TODO Auto-generated method stub
        StringBuffer sb = new StringBuffer("select * FROM " + formBean.getMasterTableBean().getTableName());
        sb.append(" WHERE " + formBean.getFieldBeanByDisplay("经销商名称").getName());
        sb.append(" = :name AND " + formBean.getFieldBeanByDisplay("年份").getName());
        sb.append(" = :year");
        List<Map> list = JdbcAgentUtil.doQuery(sb.toString(), param);
        if (CollectionUtils.isNotEmpty(list)) {
            return (Date) list.get(0).get("start_date");
        }
        return null;
    }

    @Override
    public Long getDDAttacheByAgent(FormBean formBean, Long id) throws BusinessException {
        // TODO Auto-generated method stub
        Map param = new HashMap();
        param.put("id", id);
        StringBuffer sb = new StringBuffer("SELECT ");
        sb.append(formBean.getFieldBeanByDisplay("DD专员").getName() + " id");
        sb.append(" from " + formBean.getMasterTableBean().getTableName());
        sb.append(" WHERE " + formBean.getFieldBeanByDisplay("经销商").getName());
        sb.append(" = :id AND finishedflag=0");
        List<Map> list = JdbcAgentUtil.doQuery(sb.toString(), param);
        if (CollectionUtils.isNotEmpty(list)) {
            return Long.valueOf(list.get(0).get("id").toString());
        }
        return null;
    }

    @Override
    public List<Map> getSimsByMap(FormBean simsBean, Map params)
            throws BusinessException {
        // TODO Auto-generated method stub
        String simsTable = simsBean.getMasterTableBean().getTableName();
        StringBuilder sb = new StringBuilder("select ");
        sb.append(simsBean.getFieldBeanByDisplay("BU").getName() + " as 底表BU");
        sb.append("," + simsBean.getFieldBeanByDisplay("DstrDstrLvlName").getName() + " as level");
        sb.append("," + simsBean.getFieldBeanByDisplay("DstrDstrClassName").getName() + " as clname");
        sb.append(" ," + simsBean.getFieldBeanByDisplay("DD_Status").getName() + " as DD");
        sb.append(" ," + simsBean.getFieldBeanByDisplay("DD_Date").getName() + " as 开始时间");
        sb.append(" ," + simsBean.getFieldBeanByDisplay("DD_DATE_END").getName() + " as 结束时间");
        sb.append(" from " + simsTable);
        sb.append(" where 1=1 ");// + simsBean.getFieldBeanByDisplay("DstrCoopStatusName").getName() +"=:status");
        //params.put("status", "合作中");
        if (params.containsKey("name")) {
            sb.append(" AND " + simsBean.getFieldBeanByDisplay("经销商名称").getName() + " = :name ");
        }
        if (params.containsKey("bu")) {
            if (params.containsKey("notBU")) {
                sb.append(" AND " + simsBean.getFieldBeanByDisplay("BU").getName() + " <> :bu ");
            } else {
                sb.append(" AND " + simsBean.getFieldBeanByDisplay("BU").getName() + " = :bu ");
            }
        }
        sb.append(" order by modify_date desc");
        return JdbcAgentUtil.doQuery(sb.toString(), params);
    }

    @Override
    public boolean checkAgentNotInFlow(FormBean formBean, Map param)
            throws BusinessException {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder("select * from ");
        sb.append(formBean.getMasterTableBean().getTableName());
        sb.append(" WHERE state=1 AND finishedflag=0");
        if (param.containsKey("name")) {
            sb.append(" AND " + formBean.getFieldBeanByDisplay("经销商名称").getName() + "=:name");
        }
        if (param.containsKey("bu")) {
            sb.append(" AND " + formBean.getFieldBeanByDisplay("产品线").getName() + "=:bu");
        }
        if (param.containsKey("masterId")) {
            sb.append(" AND id !=:masterId");
        }
        List list = JdbcAgentUtil.doQuery(sb.toString(), param);
        if (CollectionUtils.isNotEmpty(list)) {
            return true;
        }
        return false;
    }

    @Override
    public Date getRecentMonth(FormBean formBean, Map params) throws BusinessException {
        StringBuilder sb = new StringBuilder("select start_date from ");
        sb.append(formBean.getMasterTableBean().getTableName());
        sb.append(" WHERE state=1 AND finishedflag=1");
        if (params.containsKey("name")) {
            sb.append(" AND " + formBean.getFieldBeanByDisplay("经销商名称").getName() + "=:name");
        }
        sb.append(" order by start_date desc");
        List<Map> list = JdbcAgentUtil.doQuery(sb.toString(), params);
        if (CollectionUtils.isNotEmpty(list)) {
            return (Date) list.get(0).get("start_date");
        }
        return null;
    }

    @Override
    public String getProductAbridge(FormBean formBean, String name)
            throws BusinessException {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder("select ");
        sb.append(formBean.getFieldBeanByDisplay("缩写").getName() + " as 表单bu");
        sb.append(" from " + formBean.getMasterTableBean().getTableName());
        sb.append(" where " + formBean.getFieldBeanByDisplay("产品线名称").getName() + "=:bu");
        Map params = new HashMap();
        params.put("bu", name);
        List<Map> list = JdbcAgentUtil.doQuery(sb.toString(), params);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0).get("表单bu").toString();
        }
        return null;
    }

    @Override
    public void updateAgentStatus(Map params) throws BusinessException {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder("update ");
        sb.append(params.get("table") + " set ");
        sb.append(params.get("field") + "=?,");
        sb.append(params.get("keyName") + "=?");
        sb.append(" where id=?");
        List list = new ArrayList();
        list.add(params.get("value"));
        list.add(params.get("keyValue"));
        list.add(params.get("id"));
        JdbcAgentUtil.doUpdateOrInsert(sb.toString(), list);
    }

    @Override
    public List<Map> checkAgentInSims(FormBean formBean, Map param) throws BusinessException {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder("select ");
        sb.append(formBean.getFieldBeanByDisplay("BU").getName() + " as bu");
        sb.append("," + formBean.getFieldBeanByDisplay("DstrDstrLvlName").getName() + " as level");
        sb.append("," + formBean.getFieldBeanByDisplay("DstrDstrClassName").getName() + " as clname");
        sb.append(" from " + formBean.getMasterTableBean().getTableName());
        sb.append(" where 1=1");
        if (param.containsKey("name")) {
            sb.append(" and " + formBean.getFieldBeanByDisplay("经销商名称").getName() + "=:name");
        }
        if (param.containsKey("status")) {
            sb.append(" and " + formBean.getFieldBeanByDisplay("DstrCoopStatusName").getName() + "=:status");
        }
        if (param.containsKey("bu")) {
            sb.append(" and " + formBean.getFieldBeanByDisplay("BU").getName() + "=:bu");
        }
        return JdbcAgentUtil.doQuery(sb.toString(), param);
    }

    @Override
    public boolean isCompliance(FormBean formBean, Map param)
            throws BusinessException {
        boolean flag = false;
        StringBuilder sb = new StringBuilder("select * from ");
        sb.append(formBean.getMasterTableBean().getTableName());
        sb.append(" LEFT JOIN CTP_ENUM_ITEM ON CTP_ENUM_ITEM.ID = " + formBean.getFieldBeanByDisplay("是否需要经销商填写").getName());
        sb.append(" where  " + formBean.getMasterTableBean().getTableName() + ".state=1 AND finishedflag=0");
        if (param.containsKey("name")) {
            sb.append(" and " + formBean.getFieldBeanByDisplay("经销商ID").getName() + "=:name");
        }
        log.info("isCompliance is map:" + param.toString());
        log.info("isCompliance is sql : " + sb.toString());
        List list = JdbcAgentUtil.doQuery(sb.toString(), param);
        if (CollectionUtils.isNotEmpty(list)) {
            log.info("isCompliance is map : " + list.get(0));
            Map<String, Object> result = (Map<String, Object>) list.get(0);
            String showValue = MapUtils.getString(result, "showvalue");
            log.info("isCompliance is showvalue : " + showValue);
            if ("是".equals(showValue)) {
                if (StringUtils.isNotBlank(MapUtils.getString(param, "dealerContext"))) {
                    flag = true;
                }
            } else {
                flag = true;
            }
        }
        log.info("isCompliance is return : " + flag);
        return flag;
    }

    @Override
    public Map<String, Object> findByNo(FormBean formBean, Map param) throws BusinessException {
        StringBuilder sb = new StringBuilder("select * from ");
        sb.append(formBean.getMasterTableBean().getTableName());
        sb.append(" where  state=1 AND finishedflag=0");
        if (param.containsKey("name")) {
            sb.append(" and " + formBean.getFieldBeanByDisplay("经销商ID").getName() + "=:name");
        }
        log.info("findByNo is map:" + param.toString());
        log.info("findByNo is sql : " + sb.toString());
        List<Map> datList = JdbcAgentUtil.doQuery(sb.toString(), param);
        if (!datList.isEmpty()) {
            return datList.get(0);
        }
        return null;
    }

    @Override
    public FlipInfo findLogList(Date date, FormBean formBean, FlipInfo flipInfo) throws BusinessException {
        Map params = new HashMap();
        StringBuilder sb = new StringBuilder("select ");
        sb.append(formBean.getFieldBeanByDisplay("操作人").getName() + " as 操作人, ");
        sb.append(formBean.getFieldBeanByDisplay("操作人wwid").getName() + " as 操作人wwid, ");
        sb.append(formBean.getFieldBeanByDisplay("表单名").getName() + " as 表单名, ");
        sb.append(formBean.getFieldBeanByDisplay("表单标题").getName() + " as 表单标题, ");
        sb.append(formBean.getFieldBeanByDisplay("操作时间").getName() + " as 操作时间, ");
        sb.append(formBean.getFieldBeanByDisplay("接收时间").getName() + " as 接收时间, ");
        sb.append(formBean.getFieldBeanByDisplay("流程ID").getName() + " as 流程id, ");
        sb.append(formBean.getFieldBeanByDisplay("操作说明").getName() + " as 操作说明, ");
        sb.append(formBean.getFieldBeanByDisplay("流程节点名").getName() + " as 流程节点名, ");
        sb.append(formBean.getFieldBeanByDisplay("动作内容").getName() + " as 动作内容, ");
        sb.append(formBean.getFieldBeanByDisplay("审批状态").getName() + " as 审批状态, ");
        sb.append(formBean.getFieldBeanByDisplay("有效处理时长").getName() + " as 有效处理时长, ");
        sb.append(formBean.getFieldBeanByDisplay("首次查看时间").getName() + " as 首次查看时间, ");
        sb.append(formBean.getFieldBeanByDisplay("审批意见").getName() + " as 审批意见, ");
        sb.append("'' as 流水号 ");
//    	sb.append(formBean.getFieldBeanByDisplay("").getName() + " as , ");
        sb.append(" from " + formBean.getMasterTableBean().getTableName());
        if (null != date) {
            params.put("date", date);
            sb.append(" where start_date >= :date");
        }
        sb.append(" order by start_date");
        flipInfo = JdbcAgentUtil.doQuery(sb.toString(), params, flipInfo);
        return flipInfo;
    }
}
